package graduate.wangyaqi.UploadFile;

import graduate.wangyaqi.Service.CmdHelper;
import graduate.wangyaqi.Service.FileHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping(path="/UploadFile")
public class UploadFileController {
    @Autowired
    private UploadFileService fileService;

    @GetMapping(path="/findById")
    public Optional<UploadFile> findById(Long aLong){
        return fileService.findById(aLong);
    }

    @GetMapping(path="/getAll")
    public Iterable<UploadFile> getAll(){
        return fileService.getAll();
    }

    // 上传文件
    @PostMapping(path="/insert")
    public boolean InsertQuestion(@RequestBody UploadFile item){
        item.setFileTime(new Date());
        fileService.save(item);
        return true;
    }

    // 编译C语言
    @PostMapping(path="/ValidateC")
    public String ValidateC(@RequestBody String program){
        String cFileName="a.c";
        FileHelper.delFile(cFileName);
        boolean isCreate = FileHelper.createFile(cFileName,program);
        if (isCreate) {
            List<String> list=new ArrayList<String>();
            list.add("g++ /root/files/a.c -o /root/files/a");
            list.add("/root/files/a");
            String res = CmdHelper.exeCmd(list.toArray(new String[list.size()]));
            return res;
        }
        return "";
    }

    @GetMapping(path="/del_download")
    public String Download(HttpServletResponse res,@RequestParam("id") Long id) throws IOException{
        Optional<UploadFile>  item = fileService.findById(id);
        if(Optional.ofNullable(item)==null){
            return "文件不存在";
        }
        int count= item.get().getDownloadCount()+1;
        item.get().setDownloadCount(count);
        fileService.save(item.get() );
        String path=item.get().getFilePath();
        String fileName= item.get().getFileName();
//        fileName= URLEncoder.encode(fileName,"UTF-8");
        File file = new File(path);
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "下载文件异常："+e.getMessage();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return "关闭文件异常："+e.getMessage();
                }
            }
        }
        return "";
    }

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    ResponseEntity<InputStreamResource> DownloadFile(@RequestParam("id") Long id)
            throws IOException {
        Optional<UploadFile>  item = fileService.findById(id);
        if(Optional.ofNullable(item)==null){
            return ResponseEntity.badRequest().body(null);
        }
        int count= item.get().getDownloadCount()+1;
        item.get().setDownloadCount(count);
        fileService.save(item.get() );
        String filePath = item.get().getFilePath();
        FileSystemResource file = new FileSystemResource(filePath);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }

    /**
     * 文件上传具体实现方法;
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public String handleFileUpload(@RequestParam("file")MultipartFile file,@RequestParam("user") String user){
        if(!file.isEmpty()){
            try {
                SimpleDateFormat format= new SimpleDateFormat("yyyyMMddhhmmss");
                String filePath="/root/files/"
                        + format.format(new Date()) + file.getOriginalFilename();
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
                out.write(file.getBytes());
                out.flush();
                out.close();

                UploadFile upFile=new UploadFile();
                upFile.setFileTime(new Date());
                upFile.setFileName(file.getOriginalFilename());
                upFile.setFilePath(filePath);
                upFile.setUploadUser(user);
                fileService.save(upFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "上传失败,"+e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败,"+e.getMessage();
            }
            return "上传成功";
        }else{
            return "上传失败，因为文件是空的.";
        }
    }
}
